
package com.ivo.quartz;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.ivo.core.hibernate.HibernateInvoker;
import com.ivo.sys.Code;
import com.ivo.sys.CodeManager;
import com.ivo.util.StringUtil;



@Repository
public class OperationQuartz {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	 @Autowired
	 private HibernateInvoker hibernateInvoker;
	 
	 @Autowired
	 private CodeManager codeManager;
	
	 @Resource(name = "dsEdw")
	 private DataSource dsEdwDataSource;
		
	 @Resource(name = "scmdataSource")
	 private DataSource scmdataSource;

		@Transactional
		@Scheduled(cron = "0 0 0 16 * ? ")
		public void execute() throws SQLException {
		
		logger.info("同步FHR站点start");
		RestTemplate restTemplate = new RestTemplate();
		JsonParser parser = new JsonParser();
		String url = "http://myivo.ivo.com.cn/FHR/restful/getOperation.do";
		String json = restTemplate.getForObject(url, String.class); 
		String Operation_ID = "";
		String OperationName = "";
		String Scope = "";
		String ParentDepartment_ID = "";
		String Department_ID = "";
		String hql1 = "from Code where isValid = true";
		String hql2 = "from Code c where isValid = true and c.category in ('5','24','25','28','29','38','39')";
		List<Code> codeList1 = hibernateInvoker.find(Code.class,hql1);
		List<Code> codeList2 = hibernateInvoker.find(Code.class,hql2);
	    JsonArray Jarray   = parser.parse(json).getAsJsonArray();
	    
	    for(Code co : codeList2){
	    	for(int i = 0; i<Jarray.size();i++){
	    		boolean isExist = false;
	    		Operation_ID = Jarray.get(i).getAsJsonObject().get("Operation_ID").getAsString();
	    		if(co.getName().equals(Operation_ID)){
	    			isExist = true;
	    			break;
	    		}
	    		if(i == Jarray.size()-1 && isExist == false){
	    			Code tempCode = hibernateInvoker.findUnique(Code.class, "from Code co where isValid = true AND co.name ='" + co.getName() + "'");
	    			tempCode.setIsValid(false);
	    		}
	    	}
	    	 
	    	 
	    }
	    
	    for(int i =0; i<Jarray.size();i++){
	    	Operation_ID = Jarray.get(i).getAsJsonObject().get("Operation_ID").getAsString();
	    	OperationName = Jarray.get(i).getAsJsonObject().get("OperationName").getAsString();
	    	Scope = Jarray.get(i).getAsJsonObject().get("Scope").getAsString();
	    	ParentDepartment_ID = Jarray.get(i).getAsJsonObject().get("ParentDepartment_ID").getAsString();
	    	Department_ID = Jarray.get(i).getAsJsonObject().get("Department_ID").getAsString();
	    	for(Code co : codeList1){
	    		if(!Operation_ID.equals(co.getName())){
	    			Code tempCode = hibernateInvoker.findUnique(Code.class, "from Code co where isValid = true AND co.name ='" + Operation_ID + "'");
	    			if(tempCode == null){
	    			if(Scope.equals("ARY")){
		    			Code code = new Code();
		    			if(ParentDepartment_ID.equals("10000024")){
		    				code.setName(Operation_ID);
			    			code.setLabel(OperationName);
			    			code.setCategory(Long.parseLong("28"));
			    			codeManager.save(code);
		    			}else{
		    				code.setName(Operation_ID);
			    			code.setLabel(OperationName);
			    			code.setCategory(Long.parseLong("29"));
			    			codeManager.save(code);
		    			}
	    			}else if(Scope.contains("M")){
	    				
	    				if(ParentDepartment_ID.equals("10000693") || ParentDepartment_ID.equals("10000694") || ParentDepartment_ID.equals("10000695")){
		    				if(Scope.equals("M1")){
		    					Code code = new Code();
				    			code.setName(Operation_ID);
				    			code.setLabel(OperationName);
				    			code.setCategory(Long.parseLong("38"));
				    			codeManager.save(code);
		    				}else if(Scope.equals("M2")){
			    				Code code = new Code();
				    			code.setName(Operation_ID);
				    			code.setLabel(OperationName);
				    			code.setCategory(Long.parseLong("39"));
				    			codeManager.save(code);
			    			
			    			}
		    			}else{
		    				if(Scope.equals("M1")){
		    					Code code = new Code();
				    			code.setName(Operation_ID);
				    			code.setLabel(OperationName);
				    			code.setCategory(Long.parseLong("24"));
				    			codeManager.save(code);
		    				}else if(Scope.equals("M2")){
			    				Code code = new Code();
				    			code.setName(Operation_ID);
				    			code.setLabel(OperationName);
				    			code.setCategory(Long.parseLong("25"));
				    			codeManager.save(code);
			    			
			    			}
		    			}
	    			}
	    		}
	    		}
	    	}
	    }
		
	    logger.info("同步FHR站点end");
	    
	    
	    
	    logger.info("同步MDC站点start");
	    long startTime = System.currentTimeMillis();
	    Map<String, String> M1Ope = new LinkedHashMap<String, String>();
		Map<String, String> M2Ope = new LinkedHashMap<String, String>();
		Map<String, String> insertMap = new LinkedHashMap<String, String>();
	    JdbcTemplate dsEdwTemplate = new JdbcTemplate(dsEdwDataSource);
	    dsEdwTemplate.query("SELECT OPE_ID,OPE_NAME FROM DM.M_OPE_D  WHERE OPE_ID LIKE '11M%' OR OPE_ID LIKE '10M%' ORDER BY OPE_ID", new RowCallbackHandler() {

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String ope = rs.getString(1);
				String ope_name = rs.getString(2);
				String scope = ope.substring(0,3);
				String ope_id = ope.substring(3);
				if(scope.equals("10M")){
					M1Ope.put(ope_id, ope_name);
					insertMap.put(ope_id, ope_name);
					}
				
				if(scope.equals("11M")){
					M2Ope.put(ope_id, ope_name);
				}
				for(Map.Entry<String, String> ope2 : M1Ope.entrySet()){
					int size = insertMap.size();
					for(Map.Entry<String, String> ope1 : M1Ope.entrySet()){
						if(ope1.getKey().equals(ope2.getKey())){
							if(!ope1.getValue().equals(ope2.getValue())){
								insertMap.put(ope2.getKey(), ope2.getValue());
							}
							break;
						}
					}
					if(insertMap.size() == size){
						insertMap.put(ope2.getKey(), ope2.getValue());
					}
				}
				for(Map.Entry<String, String> op : insertMap.entrySet()){
					Code co = hibernateInvoker.findUnique(Code.class, "from Code co where isValid = true AND co.category = '26' AND co.name ='" + op.getKey() + "'AND co.label ='" + op.getValue() + "'");
					if(co == null){
						Code code = new Code();
			    		code.setName(op.getKey());
			    		code.setLabel(op.getValue());
			    		code.setCategory(Long.parseLong("26"));
			    		codeManager.save(code);
					}
				}
				
			}
		});
	    logger.info("同步MDC站点end");
	    logger.info("耗时: " + (System.currentTimeMillis() - startTime));
	    
	    
	    
	    
	    
	    logger.info("同步APS站点start");
	    JdbcTemplate ScmTemplate = new JdbcTemplate(scmdataSource);
	    ScmTemplate.query("SELECT DISTINCT OPE FROM scm_aps_lcm_rlbp WHERE FAB_ID IN('M1','M2','LCM1','LCM2')", new RowCallbackHandler() {

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String ope = rs.getString(1);
				if(StringUtil.isNotEmpty(ope)){
				Code tempCode = hibernateInvoker.findUnique(Code.class, "from Code co where isValid = true AND co.category = '27' AND co.name ='" + ope + "'");
				if(tempCode == null){
						Code code = new Code();
			    		code.setName(ope);
			    		code.setLabel(ope);
			    		code.setCategory(Long.parseLong("27"));
			    		codeManager.save(code);
					}
			}}
		});
	    logger.info("同步APS站点end");
	  
 }

}